﻿using ArtMath.Attribute;
using ArtMath.Core.Helper;
using ArtMath.Resource;
using System;
using System.ComponentModel;
using ArtMath.Data;

namespace ArtMath.Component.Line
{
    /// <summary>
    /// 导函数
    /// </summary>
    [Serializable]
    public class DerivationFunction : Function
    {
        Function oriFunc;
        int times;
        public DerivationFunction(SketchPad pad, string name, Function func, int times, bool addToList = true) : base(pad, name, ToolTypeName.dhs, null, null, addToList)
        {
            OriginalFunction = func;
            DerivativeOrder = times;
        }
        [Browsable(false)]
        public override string IndependentVariable
        {
            get
            {
                return base.IndependentVariable;
            }

            set
            {
                base.IndependentVariable = value;
            }
        }
        [MultilingualCategory("Parameter"), ReadOnly(true)]
        public override ManualParameterStringX FunctionExpression
        {
            get
            {
                return base.FunctionExpression;
            }

            set
            {
                base.FunctionExpression = value;
            }
        }
        [MultilingualCategory("Structure"), MultilingualDisplayName("PrimitiveFunction"), TypeConverter(typeof(ExpandableObjectConverter))]
        public Function OriginalFunction
        {
            get { return oriFunc; }
            set
            {
                oriFunc?.OutChildren_Line.Remove(this);
                oriFunc = value;
                oriFunc?.OutChildren_Line.Add(this);
            }
        }
        [MultilingualCategory("Structure"), MultilingualDisplayName("DerivativeOrder"), DefaultValue(typeof(int), "1")]
        public int DerivativeOrder
        {
            get { return times; }
            set
            {
                if (value < 1)
                {
                    Pad.ShowMessage(string.Format(Resources.Translate("MustPositiveInt"), Resources.Translate("DerivativeOrder")), MessageType.Exclamation);
                }
                else
                {
                    times = value;
                    string func = OriginalFunction.FirstDerivative;
                    for (int i = 0; i < times - 1; i++)
                    {
                        Derivation der = new Derivation(func, OriginalFunction.IndependentVariable);
                        try
                        {
                            func = der.GetDerivation();
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    }
                    FunctionExpression.DirectExpression = func;
                    IndependentVariable = OriginalFunction.IndependentVariable;
                }
            }
        }
    }
}
